/**
 * 渲染器基类
 * 提供通用的错误处理、DOM 观察等功能
 */
export class BaseRenderer {
  constructor() {
    this.observer = null
    this.errors = []
    this.errorCallback = null
  }

  // ========== 错误处理（统一实现）==========
  
  setErrorCallback(callback) {
    this.errorCallback = callback
  }

  getErrors() {
    return [...this.errors]
  }

  clearErrors() {
    this.errors = []
  }

  addError(errorInfo) {
    this.errors.push(errorInfo)
    if (this.errorCallback) {
      this.errorCallback(errorInfo)
    }
  }

  // ========== DOM 观察（统一实现）==========
  
  /**
   * 创建 DOM 观察器
   * @param {string} containerSelector - 容器选择器
   * @param {string} targetClass - 目标元素类名
   * @param {Function} callback - 检测到变化时的回调
   * @param {number} debounceMs - 防抖延迟（毫秒）
   */
  observeDOM(containerSelector, targetClass, callback, debounceMs = 100) {
    let debounceTimer = null
    
    this.observer = new MutationObserver((mutations) => {
      let shouldUpdate = false
      
      for (const mutation of mutations) {
        if (mutation.addedNodes.length > 0) {
          const hasTarget = Array.from(mutation.addedNodes).some(node => {
            if (node.nodeType === 1) {
              return node.classList?.contains(targetClass) || 
                     node.querySelector?.(`.${targetClass}`)
            }
            return false
          })
          
          if (hasTarget) {
            shouldUpdate = true
            break
          }
        }
      }
      
      if (shouldUpdate) {
        if (debounceTimer) clearTimeout(debounceTimer)
        debounceTimer = setTimeout(() => callback(), debounceMs)
      }
    })

    const container = document.querySelector(containerSelector)
    if (container) {
      this.observer.observe(container, { childList: true, subtree: true })
    }
  }

  // ========== 资源清理（统一实现）==========
  
  cleanup() {
    if (this.observer) {
      this.observer.disconnect()
      this.observer = null
    }
    this.clearErrors()
  }
}
